import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as storage from "@/utils/storage";

export const USER_CACHE_KEY = 'user'
export const TOKEN_CACHE_KEY = 'token'

export const useUserStore = defineStore('user', () => {
  const cachedToken = storage.take<IToken>(TOKEN_CACHE_KEY)
  const cachedUser = storage.take<IUser>(USER_CACHE_KEY)
  
  const user = ref<IUser|undefined>(cachedUser)
  const token = ref<IToken|undefined>(cachedToken)

  const updateUser = (nu: IUser|undefined) => {
    storage.save(USER_CACHE_KEY, nu)
    user.value = nu
  }
  const clear = () => {
    storage.clear()
    token.value = undefined
    user.value = undefined
  }
  const updateToken = (nt: IToken) => {
    storage.save(TOKEN_CACHE_KEY, nt)
    token.value = nt
  }

  return { user, token, updateUser, clear, updateToken }
})

export default useUserStore
